package com.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MultiThreadServer {
	static Logger logger = LoggerFactory.getLogger(MultiThreadServer.class);
	private int port = 21001;
	private ServerSocket serverSocket;
	private ExecutorService executorService;// 
	private final int POOL_SIZE = 10;//

	public MultiThreadServer() throws IOException {
		serverSocket = new ServerSocket(port);
		
		executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * POOL_SIZE);
		logger.debug("服务器启动");
	}

	public void service() {
		while (true) {
			Socket socket = null;
			try {
				
				socket = serverSocket.accept();
				executorService.execute(new Handler(socket));

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	public static void main(String[] args) throws IOException {
		new MultiThreadServer().service();
	}

}



class Handler implements Runnable {

	static Logger logger = LoggerFactory.getLogger(Handler.class);
	private Socket socket;

	public Handler(Socket socket) {
		this.socket = socket;
	}

	private PrintWriter getWriter(Socket socket) throws IOException {
		OutputStream socketOut = socket.getOutputStream();
		return new PrintWriter(socketOut, true);
	}

	private BufferedReader getReader(Socket socket) throws IOException {
		InputStream socketIn = socket.getInputStream();
		return new BufferedReader(new InputStreamReader(socketIn));
	}

	public String echo(String msg) {
		return "server say:" + msg;
	}

	public void run() {
		try {
			logger.debug("New connection accepted " + socket.getInetAddress() + ":" + socket.getPort());
		
		
			BufferedReader br = getReader(socket);
			PrintWriter pw = getWriter(socket);
			pw.println("connection success");
			
			String msg = null;
			while ((msg = br.readLine()) != null) {
				logger.debug(msg);
				pw.println(echo(msg));
				if (msg.equals("bye"))
					break;
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (socket != null)
					socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	
	

}
